package com.suo.enroll.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.suo.enroll.entry.Admin;
import com.suo.enroll.service.IAdminService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@RestController
public class AuthController {

    @Resource
    private IAdminService adminService;

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Admin loginRequest, HttpSession session) {
        // 检查用户名和密码是否为空
        String username = loginRequest.getUsername();
        if (username == null || username.isEmpty()) {
            return ResponseEntity.badRequest().body("账号不准为空");
        }

        String password = loginRequest.getPassword();
        if (password == null || password.isEmpty()) {
            return ResponseEntity.badRequest().body("密码不准为空");
        }

        // 查询匹配的用户名和密码
        Admin admin = adminService.getOne(new QueryWrapper<Admin>().eq("username", username).eq("password", password));
        if (admin != null) {
            // 登录成功后，在会话中存储用户信息
            session.setAttribute("loggedInUser", username);
            return ResponseEntity.ok("登录成功");
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("用户名或密码错误");
        }
    }

}


